package se.grp03.fmtunerapp;

import se.grp03.fmtunerapp.adapters.UdpAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;


public class MainActivity extends Activity {


	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		registerListeners();
		
		scanChannels();//Scan for channels on application initialization
	}

	private void registerListeners() {
		
		ListView lv = (ListView) findViewById(R.id.scanlist);
		lv.setOnItemClickListener( new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				
			}
		});
		
	}

	/*
	 * 
	 */
	private void scanChannels() {

		sendMessage("scan");
	}

	/*
	 * Tune to a specific channel
	 */
	private void tuneChannel(String msg) {

		sendMessage(msg);

	}

	/*
	 * Sends a message to the server
	 */
	private void sendMessage(String message){

		UdpAdapter udp = new UdpAdapter(message);
		udp.doOpen();
		udp.doWrite();
		startListening(udp);

	}

	/*
	 * Starts listening for incoming messages from the server
	 */
	private void startListening(final UdpAdapter udp) {

		final int CLIENT_LISTENER_SLEEP_TIME = 1000;
		Thread listeningThread = new Thread( new Runnable() {

			@Override
			public void run() {

				String message = null;

				while( message == null ){


					try {

						message = udp.doRead();
						Thread.currentThread();
						Thread.sleep(CLIENT_LISTENER_SLEEP_TIME);

					} catch (InterruptedException e) {

						e.printStackTrace();
					}
				}
				//Done reading, so close the connection.
				udp.doClose();
				process(message);
			}
		});

		listeningThread.start();
	}
	
	protected void process(String message) {


		if(message.startsWith("Scan")){


		}else{


		}
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}